<?php
namespace app\common\upload;
use think\facade\Db;
use think\facade\Filesystem;

class LocalUpload
{
    //上传本地图片值七牛云
    public function upload($type='远程抓取')
    {
        $files = request()->file();
        $post=request()->post();
        $folder=isset($post['folder'])?$post['folder']:'news';
        if ($files) {
            try {
                validate(['image'=>'filesize:10240|fileExt:jpg|image:200,200,jpg'])
                    ->check($files);
                $file=array_shift($files);
                $save_name=Filesystem::disk('public')->putFile( $folder, $file);
                $url ='/storage/'.$save_name;//替换\斜杠
                $file_title=str_replace('\\','/',$file->getOriginalName());//替换\斜杠
                return array("code"=>0, 'url' =>$url, 'originalName' => $file_title,"fileName"=>$save_name,"localPath"=>".".$url);
            } catch (think\exception\ValidateException $e) {
                return array("code"=>500,'title' => $e->getMessage());
            }
        } else {
            return array("code"=>404,'state' => 'EROOR', 'title' => '上传图片为空！');
        }
    }

    //抓取远程图片保存至本地
    public function uploadLink($url,$type='远程抓取'){
        $ext=strrchr($url,'.');
        if(!$ext!='.gif'&&$ext!='.jpg'){
            return ".jpg";
        }
        $filename=time().$ext;
        $save_dir="/storage/fetch/";
        $res=self::fetchImage($url,$filename);
        if($res['error']){
            return array("code"=>404,'state' => 'EROOR', 'title' => '上传图片为空！');
        }else{
            return array("code"=>0,'state' => 'success','url' =>$save_dir.$filename, 'title' => $url);
        }
    }

    public static function fetchImage($url,$filename,$save_dir="./storage/fetch/",$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        //获取远程文件所采用的方法
        if($type){
            $ch=curl_init();
            $timeout=5;
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        //文件大小
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        unset($img,$url);
        return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
    }

}